<?php

	class CWS_Widget_Contact extends WP_Widget {

		function __construct() {
			$widget_ops = array('classname' => 'widget_cform', 'description' => 'Simple contact form' );
			parent::__construct('cform', 'Contact Form', $widget_ops);
		}

		function widget( $args, $instance ) {

			$gen_sets = theme_get_option('general', 'gen_sets');
			$_emails = isset( $gen_sets['_cform_emails']) ? $gen_sets['_cform_emails'] : '';
			if (!$_emails) $_emails = get_bloginfo('admin_email');

			extract($args);
			
			$title = apply_filters('widget_title', empty($instance['title']) ? '' : $instance['title'], $instance, $this->id_base);

			if($title && $title != '') $head = '<h3 class="widget-title">' . $title . '</h3>';

			echo $before_widget;
			if ( $title ) {
				echo '<div class="widget ' . $type . '">';
				echo $head;
			}else {
				echo '<div class="widget ' . $type . '" style="background: none;">';
			}



if ($_SERVER['REQUEST_METHOD'] == 'POST') {
		$error = false;
		$required_fields = array("your_name", "email", "message", "subject");

		foreach ($_POST as $field => $value) {
			if (get_magic_quotes_gpc()) {
				$value = stripslashes($value);
			}
			$form_data[$field] = strip_tags($value);
		}

		foreach ($required_fields as $required_field) {
			$value = trim($form_data[$required_field]);
			if(empty($value)) {
				$error = true;
				$result = $error_empty;
			}
		}

		if(!is_email($form_data['email'])) {
			$error = true;
			$result = $error_noemail;
		}

		if ($error == false) {
			$email_subject = "[" . get_bloginfo('name') . "] " . $form_data['subject'];
			$email_message = $form_data['message'] . "\n\nIP: " . wptuts_get_the_ip();
			$headers  = "From: ".$form_data['your_name']." <".$form_data['email'].">\n";
			$headers .= "Content-Type: text/plain; charset=UTF-8\n";
			$headers .= "Content-Transfer-Encoding: 8bit\n";
			wp_mail($email, $email_subject, $email_message, $headers);
			$result = $success;
			$sent = true;
		}
	}



			echo '</div>' . $after_widget;
		}

		function update( $new_instance, $old_instance ) {
			$instance = $old_instance;
			$new_instance = wp_parse_args( (array) $new_instance, array( 'title' => '', 'count' => 0) );
			$instance['title'] = strip_tags($new_instance['title']);
			$instance['count'] = $new_instance['count'] ? 1 : 0;

			return $instance;
		}

		function form( $instance ) {
			$instance = wp_parse_args( (array) $instance, array( 'title' => '', 'count' => 0, 'dropdown' => '') );
			$title = strip_tags($instance['title']);
			$count = $instance['count'] ? 'checked="checked"' : '';
	?>
			<p><label for="<?php echo $this->get_field_id('title'); ?>">Title:</label> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" />
			</p>
	<?php
		}
	}

?>